package com.bjzsly.star3.xzb.manager;

import android.text.TextUtils;

import com.bjzsly.star3.xzb.auth.TxShareUtils;
import com.bjzsly.star3.xzb.base.AppClient;
import com.bjzsly.star3.xzb.utils.SimplePostHelper;

import org.json.JSONObject;

import rx.Observable;

/**
 * Created by ly on 2017/9/29.
 */

public class UserUtils {



    //微信相关
    public static void getWxAccessToken(String code, OnUserCallBack onUserCallBack) {
        String appKey = TxShareUtils.getInstance().getWxAppId();
        String appSecert = TxShareUtils.getInstance().getWxSecert();
        doExtraTask(AppClient.getApiService().getWxAccessToken(appKey, appSecert, code, "authorization_code"), onUserCallBack);
    }

    public static void getWxRefreshOpenId(String refreshToken, OnUserCallBack onUserCallBack) {
        String appKey = TxShareUtils.getInstance().getWxAppId();
        doExtraTask(AppClient.getApiService().getWxOpenId(appKey, refreshToken, "refresh_token"), onUserCallBack);
    }

    public static void getWxUserInfo(String accessToken, String openId, OnUserCallBack onUserCallBack) {
        doExtraTask(AppClient.getApiService().getWxUserInfo(accessToken, openId), onUserCallBack);
    }

    private static void doExtraTask(Observable observable, final OnUserCallBack onUserCallBack) {
        new SimplePostHelper().normalPost(observable, new SimplePostHelper.SimpleCallBack() {
            @Override
            public void onSuccess(Object data) {
                if (onUserCallBack != null)
                    onUserCallBack.onSuccess(data);
            }

            @Override
            public void onError(String msg) {
                if (onUserCallBack != null)
                    onUserCallBack.onFail(msg);

            }

            @Override
            public void onFail(String msg) {
                if (onUserCallBack != null)
                    onUserCallBack.onFail(msg);
            }
        });
    }


    private static String buildHeadToken(String token) {
        if (token != null) {
            return "Bearer " + token;
        }
        return null;
    }



    private static void addToJson(JSONObject json, String key, String value) {
        try {
            if (json != null && !TextUtils.isEmpty(key)) {
                if (!TextUtils.isEmpty(value))
                    json.put(key, value);
                else
                    json.put(key, value + "");
            }
        } catch (Exception e) {
        }

    }

    public static void doTestUse(String token, OnUserCallBack onUserCallBack) {
        doExtraTask(AppClient.getApiService().testJwt(token), onUserCallBack);
    }

}
